package com.chapter.sample.redis.answer;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class GeoService {

    private static final String CITY = "city";

    @Autowired
    private RedisTemplate redisTemplate;

    public String geoAdd() {
        Map<String, Point> map = new HashMap<>();
        map.put("天安门", new Point(116.403963, 39.915119));
        map.put("故宫", new Point(116.403414, 39.924091));
        map.put("长城", new Point(116.024067, 40.362639));
        redisTemplate.opsForGeo().add(CITY, map);
        return map.toString();
    }

    public Point position(String member) {
        //获取经纬度
        List<Point> position = redisTemplate.opsForGeo().position(CITY, member);
        return position.get(0);
    }

    public String hash(String member) {
        //获取经纬度生成的bas32编码值geohash
        List<String> hash = redisTemplate.opsForGeo().hash(CITY, member);
        return hash.get(0);
    }

    public Distance distance(String member2, String member1) {
        //获取两个位置直接的距离
        Distance distance = redisTemplate.opsForGeo().distance(CITY, member1, member2, RedisGeoCommands.DistanceUnit.KILOMETERS);
        return distance;
    }

    public GeoResults rediuByxy() {
        //通过经度，纬度查找附近的，北京王府井位置116.418017,39.914402
        Circle within = new Circle(116.418017, 39.914402, Metrics.KILOMETERS.getMultiplier());
        //返回50条数
        RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs.
                newGeoRadiusArgs().
                includeDistance().
                includeCoordinates().
                sortDescending().
                limit(50);
        GeoResults<RedisGeoCommands.GeoLocation<String>> geoResult = redisTemplate.opsForGeo().radius(CITY, within, args);

        return geoResult;
    }

    public GeoResult radiusByMember() {
        //通过地方查找附近
        String member = "天安门";
        //返回50条
        RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.
                GeoRadiusCommandArgs.
                newGeoRadiusArgs().
                includeDistance().
                includeCoordinates().
                sortAscending().
                limit(50);

        //半径10公里内
        Distance distance = new Distance(10, Metrics.KILOMETERS);
        redisTemplate.opsForGeo().radius(CITY, member, distance, args);
        return null;
    }
}
